package com.euro.video.phone.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.euro.video.phone.dao.ArticleDao;
import com.euro.video.phone.entities.Article;
import com.euro.video.phone.utils.EvpEnum;

@Repository
@Transactional(propagation = Propagation.REQUIRED)
public class ArticleDaoImpl implements ArticleDao {
	@PersistenceContext
	private EntityManager manager;

	public Article creerArticle(Article article) throws Exception {
		manager.persist(article);
		return article;
	}

	public Article modifierArticle(Article article) throws Exception {
		return manager.merge(article);
	}

	public Article lireArticle(String nom) throws Exception {
		Query query = manager.createNamedQuery("lireArticleParNom");
		query.setParameter("nom", nom);
		return (Article) query.getSingleResult();
	}

	public Article lireArticle(long id) throws Exception {
		return manager.find(Article.class, id);
	}

	public boolean supprimerArticle(Article article) throws Exception {
		try {
			manager.remove(manager.contains(article) ? article : manager.merge(article));
			return true;
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Article> listArticlesParType(EvpEnum type) throws Exception {
		Query query = manager.createNamedQuery("listArticlesParType");
		query.setParameter("type", type);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Article> listArticlesEnPromo() throws Exception {
		Query query = manager.createNamedQuery("listArticlesEnPromo");
		return query.getResultList();
	}

	public byte[] retrouverImage(String nom) throws Exception {
		Query query = manager.createNamedQuery("imageArticle");
		query.setParameter("nom", nom);
		return (byte[]) query.getSingleResult();
	}

	@SuppressWarnings("unchecked")
	public List<Article> listArticlesRecents() throws Exception {
		Query query = manager.createNamedQuery("articlesRecents");
		query.setMaxResults(9);
		return query.getResultList();
	}

}
